<?php
namespace app\api\controller;

use app\api\model\Member as MemberModel;
use app\api\model\Vehicle;
use app\api\model\MemberPrice;
use app\api\model\MonthlyRate;
use app\api\model\ChargeAmount;
use app\api\model\Order;
use app\api\model\IdentityVerification;
use app\api\model\VehicleVerification;
use think\Request;
use think\Db;
use think\Exception;

/**
 * 会员控制器
 * Class Member
 * @package app\api\controller
 */
class Member extends BaseController
{
    /**
     * 会员登录接口
     * @param Request $request
     * @return \think\response\Json
     */
    public function login(Request $request)
    {
        // 获取请求参数
        $phone = $request->post('phone');
        $openid = $request->post('openid');
        
        // 获取用户名，支持nickname或name参数
        $name = $request->post('name', '');
        if (empty($name)) {
            $name = $request->post('nickname', '微信用户');
        }
        
        $avatar = $request->post('avatar', '');
        $gender = $request->post('gender', 0);
        
        if (empty($openid)) {
            return $this->renderError('参数错误：缺少openid');
        }
        
        // 登录逻辑
        $member = new MemberModel;
        $result = $member->login($phone, $openid, [
            'name' => $name,
            'avatar' => $avatar,
            'gender' => $gender
        ]);
        
        if ($result['code'] !== 200) {
            return $this->renderError($result['msg']);
        }
        
        return $this->renderSuccess('登录成功', [
            'token' => $result['data']['token'],
            'userInfo' => $result['data']['userInfo']
        ]);
    }
    
    /**
     * 获取会员信息
     * @param Request $request
     * @return \think\response\Json
     */
    public function info(Request $request)
    {
        // 获取当前登录会员ID
        $memberId = $this->getCurrentMemberId();
        if (empty($memberId)) {
            return $this->renderError('请先登录');
        }
        
        // 获取会员信息
        $member = MemberModel::get($memberId);
        if (!$member) {
            return $this->renderError('会员不存在');
        }
        
        return $this->renderSuccess('获取成功', $member->getInfoData());
    }
    
    /**
     * 更新会员信息
     * @param Request $request
     * @return \think\response\Json
     */
    public function update(Request $request)
    {
        // 获取当前登录会员ID
        $memberId = $this->getCurrentMemberId();
        if (empty($memberId)) {
            return $this->renderError('请先登录');
        }
        
        // 获取会员信息
        $member = MemberModel::get($memberId);
        if (!$member) {
            return $this->renderError('会员不存在');
        }
        
        // 获取请求参数
        $data = $request->only(['name', 'avatar', 'gender', 'email', 'birth_date', 'address']);
        
        // 更新会员信息
        if ($member->save($data)) {
            return $this->renderSuccess('更新成功', $member->getInfoData());
        }
        
        return $this->renderError('更新失败');
    }
    
    /**
     * 绑定手机号
     * @param Request $request
     * @return \think\response\Json
     */
    public function bindPhone(Request $request)
    {
        // 获取当前登录会员ID
        $memberId = $this->getCurrentMemberId();
        if (empty($memberId)) {
            return $this->renderError('请先登录');
        }
        
        // 获取会员信息
        $member = MemberModel::get($memberId);
        if (!$member) {
            return $this->renderError('会员不存在');
        }
        
        // 获取请求参数
        $phone = $request->post('phone');
        if (empty($phone)) {
            return $this->renderError('手机号不能为空');
        }
        
        // 检查手机号是否已被使用
        $exists = MemberModel::where('phone', $phone)
            ->where('id', '<>', $memberId)
            ->find();
        if ($exists) {
            return $this->renderError('该手机号已被其他账号使用');
        }
        
        // 更新手机号
        $member->phone = $phone;
        $member->updated_at = date('Y-m-d H:i:s');
        if ($member->save()) {
            return $this->renderSuccess('绑定成功', $member->getInfoData());
        }
        
        return $this->renderError('绑定失败');
    }
    
    /**
     * 获取当前登录会员ID
     * @return int|null
     */
    private function getCurrentMemberId()
    {
        // 获取请求中的token
        $token = $this->request->header('token');
        if (empty($token)) {
            return null;
        }
        
        // 从缓存中获取会员ID
        $memberId = cache('api_token_' . $token);
        return $memberId ?: null;
    }

    /**
     * 绑定车辆
     * @param Request $request
     * @return \think\response\Json
     */
    public function bindVehicle(Request $request)
    {
        if (!$this->checkToken()) {
            return false;
        }

        // 获取请求参数
        $plateNo = $request->post('plate_no');
        $ownerName = $request->post('owner_name');
        $idCard = $request->post('id_card');
        $drivingLicenseImg = $request->post('driving_license_img');
        $idCardImg = $request->post('id_card_img');

        if (empty($plateNo) || empty($ownerName) || empty($idCard)) {
            return $this->renderError('参数错误：缺少必要参数');
        }

        // 检查车牌号是否已经被绑定
        $existVehicle = Vehicle::where('plate_no', $plateNo)
            ->where('member_id', '<>', $this->userId)
            ->find();
        if ($existVehicle) {
            return $this->renderError('该车牌号已被其他用户绑定');
        }

        // 创建车辆记录
        $vehicle = new Vehicle;
        $vehicle->member_id = $this->userId;
        $vehicle->plate_no = $plateNo;
        $vehicle->owner_name = $ownerName;
        $vehicle->id_card = $idCard;
        $vehicle->driving_license_img = $drivingLicenseImg;
        $vehicle->id_card_img = $idCardImg;
        $vehicle->status = 1; // 默认状态为已审核通过
        $vehicle->create_time = time();

        if ($vehicle->save()) {
            return $this->renderSuccess('车辆绑定成功', [
                'auto_verify' => true,
                'vehicle_id' => $vehicle->id
            ]);
        } else {
            return $this->renderError('车辆绑定失败', null, 500);
        }
    }

    /**
     * 获取绑定的车辆列表
     * @return \think\response\Json
     */
    public function vehicleList()
    {
        if (!$this->checkToken()) {
            return false;
        }

        $vehicles = Vehicle::where('member_id', $this->userId)
            ->field('id, plate_no, owner_name, status, create_time')
            ->select();

        return $this->renderSuccess('获取成功', $vehicles);
    }

    /**
     * 获取会员价格列表
     * @return \think\response\Json
     */
    public function memberPrices()
    {
        if (!$this->checkToken()) {
            return false;
        }

        $prices = MemberPrice::field('id, name, price, duration, description')
            ->where('status', 1)
            ->select();

        return $this->renderSuccess('获取成功', $prices);
    }

    /**
     * 开通会员
     * @param Request $request
     * @return \think\response\Json
     */
    public function createMembership(Request $request)
    {
        if (!$this->checkToken()) {
            return false;
        }

        $priceId = $request->post('price_id');
        if (empty($priceId)) {
            return $this->renderError('参数错误：缺少price_id');
        }

        $price = MemberPrice::get($priceId);
        if (!$price) {
            return $this->renderError('会员价格不存在', null, 404);
        }

        // 创建订单
        $order = new Order;
        $order->member_id = $this->userId;
        $order->order_type = 'membership';
        $order->amount = $price->price;
        $order->status = 0; // 未支付
        $order->create_time = time();
        $order->extra = json_encode([
            'price_id' => $price->id,
            'duration' => $price->duration
        ]);

        if ($order->save()) {
            return $this->renderSuccess('创建订单成功', [
                'order_id' => $order->id,
                'amount' => $order->amount
            ]);
        } else {
            return $this->renderError('创建订单失败', null, 500);
        }
    }

    /**
     * 获取月租车价格列表
     * @return \think\response\Json
     */
    public function monthlyRates()
    {
        if (!$this->checkToken()) {
            return false;
        }

        $rates = MonthlyRate::field('id, name, price, duration, description')
            ->where('status', 1)
            ->select();

        return $this->renderSuccess('获取成功', $rates);
    }

    /**
     * 获取车币充值面额
     * @return \think\response\Json
     */
    public function chargeAmounts()
    {
        if (!$this->checkToken()) {
            return false;
        }

        $amounts = ChargeAmount::field('id, name, price, amount')
            ->where('status', 1)
            ->select();

        return $this->renderSuccess('获取成功', $amounts);
    }

    /**
     * 充值车币
     * @param Request $request
     * @return \think\response\Json
     */
    public function rechargeBalance(Request $request)
    {
        if (!$this->checkToken()) {
            return false;
        }

        $amountId = $request->post('amount_id');
        if (empty($amountId)) {
            return $this->renderError('参数错误：缺少amount_id');
        }

        $chargeAmount = ChargeAmount::get($amountId);
        if (!$chargeAmount) {
            return $this->renderError('充值面额不存在', null, 404);
        }

        // 创建订单
        $order = new Order;
        $order->member_id = $this->userId;
        $order->order_type = 'recharge';
        $order->amount = $chargeAmount->price;
        $order->status = 0; // 未支付
        $order->create_time = time();
        $order->extra = json_encode([
            'amount_id' => $chargeAmount->id,
            'recharge_amount' => $chargeAmount->amount
        ]);

        if ($order->save()) {
            return $this->renderSuccess('创建订单成功', [
                'order_id' => $order->id,
                'amount' => $order->amount
            ]);
        } else {
            return $this->renderError('创建订单失败', null, 500);
        }
    }

    /**
     * 获取车币余额
     * @return \think\response\Json
     */
    public function balance()
    {
        if (!$this->checkToken()) {
            return false;
        }

        $member = MemberModel::get($this->userId);
        if (!$member) {
            return $this->renderError('用户不存在', null, 404);
        }

        return $this->renderSuccess('获取成功', [
            'balance' => $member->balance
        ]);
    }

    /**
     * 微信支付接口
     * @param Request $request
     * @return \think\response\Json
     */
    public function wxPay(Request $request)
    {
        if (!$this->checkToken()) {
            return false;
        }

        $orderId = $request->post('order_id');
        if (empty($orderId)) {
            return $this->renderError('参数错误：缺少order_id');
        }

        $order = Order::where('id', $orderId)
            ->where('member_id', $this->userId)
            ->where('status', 0)
            ->find();

        if (!$order) {
            return $this->renderError('订单不存在或状态错误', null, 404);
        }

        // 调用微信支付接口，获取支付参数
        // 这里是模拟数据，实际项目中需要调用微信支付API
        $payParams = [
            'appId' => 'wx123456789',
            'timeStamp' => (string)time(),
            'nonceStr' => md5(uniqid(mt_rand(), true)),
            'package' => 'prepay_id=wx' . time(),
            'signType' => 'MD5',
            'paySign' => md5('sign' . time())
        ];

        return $this->renderSuccess('获取支付参数成功', $payParams);
    }

    /**
     * 身份证实名认证
     * @param Request $request
     * @return \think\response\Json
     */
    public function verifyIdentity(Request $request)
    {
        if (!$this->checkToken()) {
            return false;
        }

        $name = $request->post('name');
        $idCard = $request->post('id_card');

        if (empty($name) || empty($idCard)) {
            return $this->renderError('参数错误：缺少必要参数');
        }

        // 调用实名认证API，这里模拟认证成功
        $verifyTime = date('Y-m-d H:i:s');

        // 保存认证记录
        $verification = new IdentityVerification;
        $verification->member_id = $this->userId;
        $verification->name = $name;
        $verification->id_card = $idCard;
        $verification->is_verified = 1;
        $verification->verify_time = $verifyTime;
        $verification->save();

        return $this->renderSuccess('身份验证成功', [
            'is_verified' => true,
            'verify_time' => $verifyTime
        ]);
    }

    /**
     * 人车核验
     * @param Request $request
     * @return \think\response\Json
     */
    public function verifyVehicle(Request $request)
    {
        if (!$this->checkToken()) {
            return false;
        }

        $name = $request->post('name');
        $carNo = $request->post('car_no');
        $carColor = $request->post('car_color', '0');

        if (empty($name) || empty($carNo)) {
            return $this->renderError('参数错误：缺少必要参数');
        }

        // 调用人车核验API，这里模拟核验成功
        $verifyTime = date('Y-m-d H:i:s');

        // 保存核验记录
        $verification = new VehicleVerification;
        $verification->member_id = $this->userId;
        $verification->name = $name;
        $verification->car_no = $carNo;
        $verification->car_color = $carColor;
        $verification->is_verified = 1;
        $verification->verify_time = $verifyTime;
        $verification->save();

        return $this->renderSuccess('人车核验成功', [
            'is_verified' => true,
            'car_no' => $carNo,
            'verify_time' => $verifyTime
        ]);
    }

    /**
     * 获取认证状态
     * @return \think\response\Json
     */
    public function verificationStatus()
    {
        if (!$this->checkToken()) {
            return false;
        }

        // 获取身份认证状态
        $idVerification = IdentityVerification::where('member_id', $this->userId)
            ->where('is_verified', 1)
            ->order('verify_time', 'desc')
            ->find();

        // 获取车辆核验状态
        $vehicleVerifications = VehicleVerification::where('member_id', $this->userId)
            ->where('is_verified', 1)
            ->field('car_no, car_color, verify_time')
            ->select();

        $verifiedVehicles = [];
        foreach ($vehicleVerifications as $verification) {
            $verifiedVehicles[] = [
                'car_no' => $verification->car_no,
                'car_color' => $verification->car_color,
                'verify_time' => $verification->verify_time
            ];
        }

        return $this->renderSuccess('获取认证状态成功', [
            'id_verified' => !empty($idVerification),
            'id_verify_time' => $idVerification ? $idVerification->verify_time : '',
            'verified_vehicles' => $verifiedVehicles
        ]);
    }

    /**
     * 微信小程序获取手机号
     * @param Request $request
     * @return \think\response\Json
     * 
     * 小程序端调用示例：
     * <button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
     * 
     * Page({
     *   getPhoneNumber (e) {
     *     if (e.detail.errMsg === 'getPhoneNumber:ok') {
     *       // 获取成功，将code发送到服务端
     *       wx.request({
     *         url: 'https://example.com/api/member/get-phone-number',
     *         method: 'POST',
     *         data: {
     *           code: e.detail.code
     *         },
     *         header: {
     *           'content-type': 'application/json',
     *           'token': wx.getStorageSync('token')
     *         },
     *         success (res) {
     *           console.log('获取手机号成功', res.data)
     *         }
     *       })
     *     } else {
     *       console.log('用户拒绝授权获取手机号', e.detail.errMsg)
     *     }
     *   }
     * })
     */
    public function getPhoneNumber(Request $request)
    {
        // 获取请求参数
        $code = $request->post('code');
        $sessionKey = $request->post('session_key', '');
        
        if (empty($code)) {
            return $this->renderError('参数错误：缺少code');
        }
        
        // 微信配置信息
        $config = config('wechat');
        $appId = $config['app_id'];
        $appSecret = $config['app_secret'];
        
        // 获取access_token
        $accessToken = $this->getAccessToken($appId, $appSecret);
        if (!$accessToken) {
            return $this->renderError('获取access_token失败');
        }
        
        // 请求微信接口获取手机号
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$accessToken}";
        $data = [
            'code' => $code
        ];
        
        $response = $this->httpPost($url, json_encode($data));
        $result = json_decode($response, true);
        
        if (isset($result['errcode']) && $result['errcode'] == 0) {
            // 获取成功
            $phoneInfo = $result['phone_info'];
            
            // 如果已登录，则更新用户手机号
            if ($this->userId) {
                $member = MemberModel::get($this->userId);
                if ($member) {
                    $member->phone = $phoneInfo['purePhoneNumber'];
                    $member->save();
                }
            }
            
            return $this->renderSuccess('获取成功', [
                'phoneNumber' => $phoneInfo['phoneNumber'],
                'purePhoneNumber' => $phoneInfo['purePhoneNumber'],
                'countryCode' => $phoneInfo['countryCode']
            ]);
        } else {
            // 获取失败
            return $this->renderError($result['errmsg'] ?? '获取手机号失败', [
                'errcode' => $result['errcode'] ?? -1
            ]);
        }
    }
    
    /**
     * 获取微信接口调用凭证
     * @param string $appId 小程序AppID
     * @param string $appSecret 小程序AppSecret
     * @return string|bool
     */
    private function getAccessToken($appId, $appSecret)
    {
        // 尝试从缓存获取
        $accessToken = cache('wx_access_token');
        if ($accessToken) {
            return $accessToken;
        }
        
        // 请求微信接口获取access_token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
        $response = $this->httpGet($url);
        $result = json_decode($response, true);
        
        if (isset($result['access_token'])) {
            // 将access_token存入缓存，有效期设置为7000秒（微信access_token有效期为7200秒）
            cache('wx_access_token', $result['access_token'], 7000);
            return $result['access_token'];
        }
        
        return false;
    }
    
    /**
     * 发送HTTP GET请求
     * @param string $url 请求URL
     * @return string
     */
    private function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($curl);
        curl_close($curl);
        
        return $response;
    }
    
    /**
     * 发送HTTP POST请求
     * @param string $url 请求URL
     * @param string $data 请求数据
     * @return string
     */
    private function httpPost($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ]);
        $response = curl_exec($curl);
        curl_close($curl);
        
        return $response;
    }

    /**
     * 会员续费
     */
    public function renewMembership()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $level_id = input('level_id/d', 0);
        $months = input('months/d', 1);
        
        if (!$level_id || !$months) {
            return $this->renderError('参数错误');
        }
        
        // 获取会员等级信息
        $level = Db::name('member_level')->where('level_id', $level_id)->find();
        if (!$level) {
            return $this->renderError('会员等级不存在');
        }
        
        $amount = $level['price'] * $months;
        
        // 创建充值记录
        $recharge_data = [
            'member_id' => $member_id,
            'amount' => $amount,
            'recharge_type' => 'membership',
            'status' => 0,
            'remark' => "续费{$months}个月{$level['level_name']}",
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $recharge_id = Db::name('member_recharge_log')->insertGetId($recharge_data);
        
        return $this->renderSuccess([
            'recharge_id' => $recharge_id,
            'amount' => $amount,
            'level_name' => $level['level_name'],
            'months' => $months
        ]);
    }

    /**
     * 获取会员充值记录
     */
    public function memberRechargeLog()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        
        $list = Db::name('member_recharge_log')
            ->where('member_id', $member_id)
            ->order('created_at desc')
            ->paginate($limit, false, ['page' => $page]);
        
        return $this->renderSuccess($list);
    }

    /**
     * 获取缴费记录
     */
    public function paymentLog()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        
        // 获取余额变动记录和会员充值记录
        $balance_logs = Db::name('balance_log')
            ->where('member_id', $member_id)
            ->field('id, amount, remark, created_at, "balance" as type')
            ->select();
            
        $recharge_logs = Db::name('member_recharge_log')
            ->where('member_id', $member_id)
            ->where('status', 1)
            ->field('id, amount, remark, created_at, "recharge" as type')
            ->select();
        
        $all_logs = array_merge($balance_logs, $recharge_logs);
        
        // 按时间排序
        usort($all_logs, function($a, $b) {
            return strtotime($b['created_at']) - strtotime($a['created_at']);
        });
        
        // 分页
        $total = count($all_logs);
        $start = ($page - 1) * $limit;
        $list = array_slice($all_logs, $start, $limit);
        
        return $this->renderSuccess([
            'data' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ]);
    }

    /**
     * 出场车币抵扣
     */
    public function exitPayment()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $amount = input('amount/f', 0);
        $vehicle_no = input('vehicle_no/s', '');
        
        if (!$amount || !$vehicle_no) {
            return $this->renderError('参数错误');
        }
        
        // 检查余额
        $member = Db::name('members')->where('member_id', $member_id)->find();
        if ($member['balance'] < $amount) {
            return $this->renderError('余额不足');
        }
        
        // 扣除余额
        Db::startTrans();
        try {
            Db::name('members')->where('member_id', $member_id)->setDec('balance', $amount);
            
            // 记录余额变动
            Db::name('balance_log')->insert([
                'member_id' => $member_id,
                'amount' => -$amount,
                'remark' => "出场支付-{$vehicle_no}",
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            Db::commit();
            return $this->renderSuccess('支付成功');
        } catch (Exception $e) {
            Db::rollback();
            return $this->renderError('支付失败');
        }
    }

    /**
     * 会员功能车币抵扣
     */
    public function memberDiscount()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $amount = input('amount/f', 0);
        $service_type = input('service_type/s', '');
        
        if (!$amount || !$service_type) {
            return $this->renderError('参数错误');
        }
        
        // 检查是否为VIP会员
        $member = Db::name('members')->where('member_id', $member_id)->find();
        if (!$member['is_vip'] || ($member['vip_expire_time'] && strtotime($member['vip_expire_time']) < time())) {
            return $this->renderError('非VIP会员或VIP已过期');
        }
        
        // 检查余额
        if ($member['balance'] < $amount) {
            return $this->renderError('余额不足');
        }
        
        // 扣除余额
        Db::startTrans();
        try {
            Db::name('members')->where('member_id', $member_id)->setDec('balance', $amount);
            
            // 记录余额变动
            Db::name('balance_log')->insert([
                'member_id' => $member_id,
                'amount' => -$amount,
                'remark' => "会员服务-{$service_type}",
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            Db::commit();
            return $this->renderSuccess('抵扣成功');
        } catch (Exception $e) {
            Db::rollback();
            return $this->renderError('抵扣失败');
        }
    }

    /**
     * 月租车续期
     */
    public function monthlyRenew()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $vehicle_id = input('vehicle_id/d', 0);
        $months = input('months/d', 1);
        
        if (!$vehicle_id || !$months) {
            return $this->renderError('参数错误');
        }
        
        // 检查车辆是否属于该用户
        $vehicle = Db::name('vehicles')->where('id', $vehicle_id)->where('member_id', $member_id)->find();
        if (!$vehicle) {
            return $this->renderError('车辆不存在');
        }
        
        // 计算续期费用
        $monthly_rate = Db::name('monthly_rates')->where('id', 1)->value('price');
        $amount = $monthly_rate * $months;
        
        // 检查余额
        $member = Db::name('members')->where('member_id', $member_id)->find();
        if ($member['balance'] < $amount) {
            return $this->renderError('余额不足');
        }
        
        // 续期操作
        Db::startTrans();
        try {
            // 扣除余额
            Db::name('members')->where('member_id', $member_id)->setDec('balance', $amount);
            
            // 更新车辆到期时间
            $expire_time = $vehicle['expire_time'] ? $vehicle['expire_time'] : date('Y-m-d H:i:s');
            $new_expire_time = date('Y-m-d H:i:s', strtotime($expire_time . " +{$months} month"));
            Db::name('vehicles')->where('id', $vehicle_id)->update(['expire_time' => $new_expire_time]);
            
            // 记录余额变动
            Db::name('balance_log')->insert([
                'member_id' => $member_id,
                'amount' => -$amount,
                'remark' => "月租车续期{$months}个月-{$vehicle['vehicle_no']}",
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            Db::commit();
            return $this->renderSuccess([
                'new_expire_time' => $new_expire_time,
                'amount' => $amount
            ]);
        } catch (Exception $e) {
            Db::rollback();
            return $this->renderError('续期失败');
        }
    }

    /**
     * 月租暂停
     */
    public function monthlyPause()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $vehicle_id = input('vehicle_id/d', 0);
        $days = input('days/d', 1);
        
        if (!$vehicle_id || !$days) {
            return $this->renderError('参数错误');
        }
        
        // 检查车辆是否属于该用户
        $vehicle = Db::name('vehicles')->where('id', $vehicle_id)->where('member_id', $member_id)->find();
        if (!$vehicle) {
            return $this->renderError('车辆不存在');
        }
        
        // 暂停操作
        try {
            // 延长到期时间
            $expire_time = $vehicle['expire_time'];
            $new_expire_time = date('Y-m-d H:i:s', strtotime($expire_time . " +{$days} day"));
            Db::name('vehicles')->where('id', $vehicle_id)->update([
                'expire_time' => $new_expire_time,
                'pause_days' => Db::raw('pause_days + ' . $days)
            ]);
            
            return $this->renderSuccess([
                'new_expire_time' => $new_expire_time,
                'pause_days' => $days
            ]);
        } catch (Exception $e) {
            return $this->renderError('暂停失败');
        }
    }

    /**
     * 月租变更
     */
    public function monthlyChange()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $vehicle_id = input('vehicle_id/d', 0);
        $new_vehicle_no = input('new_vehicle_no/s', '');
        
        if (!$vehicle_id || !$new_vehicle_no) {
            return $this->renderError('参数错误');
        }
        
        // 检查车辆是否属于该用户
        $vehicle = Db::name('vehicles')->where('id', $vehicle_id)->where('member_id', $member_id)->find();
        if (!$vehicle) {
            return $this->renderError('车辆不存在');
        }
        
        // 检查新车牌号是否已存在
        $exists = Db::name('vehicles')->where('vehicle_no', $new_vehicle_no)->where('id', 'neq', $vehicle_id)->find();
        if ($exists) {
            return $this->renderError('新车牌号已存在');
        }
        
        // 变更操作
        try {
            Db::name('vehicles')->where('id', $vehicle_id)->update([
                'vehicle_no' => $new_vehicle_no,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            
            return $this->renderSuccess('变更成功');
        } catch (Exception $e) {
            return $this->renderError('变更失败');
        }
    }
}